package com.yike.websocket.util;

import com.alibaba.fastjson.JSON;
import com.yike.websocket.param.MessageReminderParam;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.SendHandler;
import javax.websocket.SendResult;
import javax.websocket.Session;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Sakura
 * @date 2024/9/13 11:40
 */
@Log4j2
@Component
public class MessageReminderUtil {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessageReminder(String userId, MessageReminderParam messageReminderParam) {
        Session session = WebsocketUtil.getSession(userId);
        if (session == null) {
            log.info("sendMessageReminder 消息发送失败：用户 " + userId + " 不在线");
            messageReminderParam.setWebsocketStatus(0);
            org.apache.rocketmq.client.producer.SendResult sendResult = rocketMQTemplate.syncSend("message_reminder_topic", messageReminderParam, 3000);
            log.info("message_reminder_topic" + " 推送到队列结果：" + sendResult);
            return;
        }
        session.getAsyncRemote().sendText(JSON.toJSONString(messageReminderParam), result -> {
            if (result.isOK()) {
                log.info("sendMessageReminder 消息发送成功");
                messageReminderParam.setWebsocketStatus(1);
//                // 如果推送成功则表示消息已读
//                messageReminderParam.setMsgStatus(1);
                org.apache.rocketmq.client.producer.SendResult sendResult = rocketMQTemplate.syncSend("message_reminder_topic", messageReminderParam, 3000);
                log.info("message_reminder_topic" + " 推送到队列结果：" + sendResult);
            } else {
                log.warn("sendMessageReminder 消息发送失败: " + result.getException());
                messageReminderParam.setWebsocketStatus(0);
                org.apache.rocketmq.client.producer.SendResult sendResult = rocketMQTemplate.syncSend("message_reminder_topic", messageReminderParam, 3000);
                log.info("message_reminder_topic" + " 推送到队列结果：" + sendResult);

            }
        });
    }

}